<!-- 回答问卷suveryjs公用组件 -->
<template>
  <div class="survey-content tdesign-starter-layout">
    <vue-html2pdf
      ref="html2Pdf"
      :show-layout="true"
      :float-layout="false"
      :enable-download="false"
      :preview-modal="false"
      :filename="fileName"
      :pdf-quality="2"
      :manual-pagination="false"
      :paginate-elements-by-height="0"
      pdf-format="a4"
      pdf-content-width="100%"
      pdf-orientation="portrait"
      @beforeDownload="beforeDownload"
    >
      <section slot="pdf-content">
        <!-- PDF Content Here -->
        <survey
          class="survey"
          :class="{ preview: questionnaireStatus === QUESTIONNAIRE_STATUS.PREVIEW }"
          :survey="survey"
        />
      </section>
    </vue-html2pdf>
    <t-loading
      :loading="isShowLoading"
      :text="loadingText"
      attach="body"
      fullscreen
      indicator
      preventScrollThrough
      showOverlay
    />
  </div>
</template>

<script>
// https://github.com/kempsteven/vue-html2pdf
// https://www.npmjs.com/package/html2pdf.js#usage
// http://raw.githack.com/MrRio/jsPDF/master/docs/jsPDF.html
import VueHtml2pdf from 'vue-html2pdf';

import { StylesManager, Model } from 'survey-vue';
import 'survey-vue/defaultV2.css';
import { FILE_URL_PREFIX } from '@/constants/index';
import { ANSWER_ACTIONS, QUESTIONNAIRE_STATUS } from '@/constants/risk-assessment-management';
import { riskOptions, RISK_STATUS } from '@/constants/risk-assessment-template';
import { requestUploadFile } from '@/service/upload';

StylesManager.applyTheme('defaultV2');

export default {
  name: 'surveyContent',
  components: { VueHtml2pdf },
  props: {
    value: {
      type: Object,
      default() {
        return {};
      },
    },
    isReviewor: {
      type: Boolean,
      default: false,
    },
    fileName: {
      type: String,
      default: '评估报告',
    },
    questionObject: {
      type: Object,
      default() {
        return {};
      },
    },
    riskObject: {
      type: Object,
      default() {
        return {};
      },
    },
    questionnaireStatus: {
      type: Number,
      default: QUESTIONNAIRE_STATUS.TO_BE_FILLED,
    },
  },
  data() {
    // surveyJS初始化
    const survey = new Model({
      pageNextText: '下一页',
      pagePrevText: '上一页',
      completeText: '完成',
      showQuestionNumbers: 'off',
      // showNavigationButtons: false,
      // checkErrorsMode: 'onValueChanged',
      // showPrevButton: false,
    });
    // 在每页页面渲染之前的处理
    survey.onAfterRenderPage.add((survey, options) => {
      if (!this.questionnaireStatus) return;
      const questionEl = options.htmlElement;

      if (questionEl.querySelector('.page-header-right')) return;
      const header = questionEl.querySelector('.sd-title');
      header.style = 'display: flex;justify-content: space-between;align-items: center;width: 100%;';

      // 当前页面为待填写状态时的处理
      if (this.questionnaireStatus === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        // 判断此页是否有可作答题，有则渲染整页流转按钮
        const questionNameArr = [];
        options.page.elements?.forEach((element) => {
          if (!element.readOnly && element.isVisible && !element.isPanel) questionNameArr.push(element.name);
          element.elements?.forEach((panel_element) => {
            if (!panel_element.readOnly && panel_element.isVisible) questionNameArr.push(panel_element.name);
          });
        });
        if (questionNameArr.length === 0) return;
        const button = document.createElement('div');
        button.className = 'page-header-right';
        button.style =
          'margin-right: 10px;width: 50px;height: 100%;display: flex;justify-content: space-between;align-items:center;cursor: pointer;';
        // if (options.page.readOnly) button.style.display = 'none';
        button.innerHTML = `
        <img src="./images/survey-button-2.svg" style="width: 16px; height: 16px;cursor: pointer;"/>
        <span style="font-size: 14px;color: #0052D9;font-weight: 400;">指派</span>
      `;
        button.onclick = () => {
          const questionNameArr = [];
          options.page.elementsValue?.forEach((element) => {
            if (element.isQuestion && !element.readOnly && element.isVisible) questionNameArr.push(element.name);
            element.elementsValue?.forEach((panel_element) => {
              if (!panel_element.readOnly && panel_element.isVisible) questionNameArr.push(panel_element.name);
            });
          });
          this.$emit('handleActions', ANSWER_ACTIONS.ASSIGNED, questionNameArr.join(','));
        };
        header.appendChild(button);
      }

      // 当前页面为待审核\已完成状态时的处理
      if (
        this.questionnaireStatus === QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED ||
        this.questionnaireStatus === QUESTIONNAIRE_STATUS.COMPLETED
      ) {
        // 渲染问题计数的信息
        let count = 0;
        options.page.elements?.forEach((element) => {
          if (element.isVisible && !element.isPanel) count += 1;
          element.elements?.forEach((panel_element) => {
            if (panel_element.isVisible) count += 1;
          });
        });
        const pageInfoEl = document.createElement('span');
        pageInfoEl.className = 'page-header-right page-question-count';
        pageInfoEl.style = 'font-weight: 400;font-size: 14px;color: #777777 ';
        pageInfoEl.innerHTML = `共计${count}个问题`;
        header.appendChild(pageInfoEl);
      }
    });
    // 在每个问题渲染之前的处理
    survey.onAfterRenderQuestion.add((survey, options) => {
      if (!this.questionnaireStatus) return;
      const questionInfo = this.questionObject[options.question.name];
      if (!questionInfo) return;
      const questionEl = options.htmlElement;

      // 只有不是预览状态时且有问题描述进行的操作
      if (this.questionnaireStatus !== QUESTIONNAIRE_STATUS.PREVIEW && options.question.description) {
        // 渲染每个问题的tip提示描述信息
        const titleEl = questionEl.querySelector('.sv-vue-title-additional-div');
        const tipContentEl = document.createElement('div');
        tipContentEl.className = 'sv-tip-content';
        tipContentEl.innerHTML = `
            <img class="sv-tip-img" src="./images/survey-tip.png">
            <div class="t-popup">
              <div class="t-popup__content">
                ${options.question.description}
              </div>
            </div>
          `;
        titleEl.appendChild(tipContentEl);
      }

      //  只有不是预览状态时才渲染操作盒子
      if (this.questionnaireStatus !== QUESTIONNAIRE_STATUS.PREVIEW) {
        const header = questionEl.querySelector('.sd-title');
        header.style = 'display: flex;justify-content: space-between;opacity: 1;';
        header.firstElementChild.className = 'sv-vue-title-additional-div';
        if (this.questionnaireStatus === QUESTIONNAIRE_STATUS.TO_BE_FILLED && options.question.readOnly) {
          header.querySelector('.sv-vue-title-additional-div').style.opacity = 0.5;
        }

        const actionItems = {
          [QUESTIONNAIRE_STATUS.TO_BE_FILLED]: [
            ANSWER_ACTIONS.FLAG,
            ANSWER_ACTIONS.ASSIGNED,
            ANSWER_ACTIONS.UPLOAD,
            ANSWER_ACTIONS.MESSAGE,
            ANSWER_ACTIONS.HISTORY,
          ],
          [QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED]: [
            ANSWER_ACTIONS.UPLOAD,
            ANSWER_ACTIONS.MESSAGE,
            ANSWER_ACTIONS.HISTORY,
          ],
          [QUESTIONNAIRE_STATUS.COMPLETED]: [ANSWER_ACTIONS.UPLOAD, ANSWER_ACTIONS.MESSAGE, ANSWER_ACTIONS.HISTORY],
          [QUESTIONNAIRE_STATUS.EXPIRED]: [ANSWER_ACTIONS.UPLOAD, ANSWER_ACTIONS.MESSAGE, ANSWER_ACTIONS.HISTORY],
        };
        // 只有是审核人且是单选多选是否题才可修改数据
        if (this.isReviewor && ['radiogroup', 'checkbox', 'boolean'].includes(questionInfo.type)) {
          actionItems[QUESTIONNAIRE_STATUS.TO_BE_RIVIEWED].unshift(ANSWER_ACTIONS.EDIT);
        }

        const buttonBox = document.createElement('div');
        buttonBox.className = 'actions-button-box';
        buttonBox.style =
          'background: #ECF2FE;border-radius: 16px;width: 148px;height: 24px;display: flex;justify-content: space-around;align-items:center;opacity:1;';
        // if (options.question.readOnly) buttonBox.style.display = 'none';
        actionItems[this.questionnaireStatus].forEach((i) => {
          const buttonItemEl = document.createElement('div');
          const img = document.createElement('img');
          buttonItemEl.className = `button-box__content`;
          img.src = `./images/survey-button-${i}.svg`;
          img.className = `button-box__item box__item-${i}`;
          buttonItemEl.style = 'cursor: pointer';
          img.onclick = () => {
            this.$emit('handleActions', i, options.question.name, options.htmlElement, options.question.id);
          };

          const span = document.createElement('span');
          span.className = `text text-${i}`;
          // 存在流转人姓名时渲染姓名框
          if (i === ANSWER_ACTIONS.ASSIGNED && questionInfo.assignedName) {
            const nameEl = document.createElement('span');
            nameEl.className = 'assigned-name';
            nameEl.innerHTML = `@ ${questionInfo.assignedName}`;
            buttonItemEl.appendChild(nameEl);
          }
          // 渲染上传文件数字
          if (i === ANSWER_ACTIONS.UPLOAD && questionInfo.fileNum > 0) {
            span.innerHTML = questionInfo.fileNum;
          }
          // 渲染留言记录数字
          if (i === ANSWER_ACTIONS.MESSAGE && questionInfo.messageNum > 0) {
            span.innerHTML = questionInfo.messageNum;
          }
          // 渲染历史记录数字
          if (i === ANSWER_ACTIONS.HISTORY && questionInfo.historyNum > 0) {
            span.innerHTML = questionInfo.historyNum;
          }

          buttonItemEl.appendChild(img);
          buttonItemEl.appendChild(span);
          buttonBox.appendChild(buttonItemEl);
        });

        header.appendChild(buttonBox);
      }

      // 如果是待填写状态且问题已被标记则渲染
      if (this.questionnaireStatus === QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        if (questionInfo.isFlag) {
          const img = questionEl.querySelector('.box__item-1');
          img.src = './images/survey-button-1-full.svg';
        }
      }

      // 当前状态不为待填写时将所有问题设置只读并渲染风险数据
      if (this.questionnaireStatus !== QUESTIONNAIRE_STATUS.TO_BE_FILLED) {
        // 审核\完成\已过期\预览页面设置为只读
        options.question.readOnly = true;
        // 只有单选多选是否题才渲染风险数据
        if (['radiogroup', 'checkbox', 'boolean'].includes(questionInfo.type)) {
          const riskBox = document.createElement('div');
          riskBox.className = `sv-riskBox sv-riskBox__${options.question.id}`;
          questionEl.appendChild(riskBox);
          this.renderRiskInfo(options.question.name, options.question.id);
        }
      }

      // 预览导出报告时，添加img标签便于导出pdf时显示图片
      if (this.questionnaireStatus === QUESTIONNAIRE_STATUS.PREVIEW && questionInfo.type === 'file') {
        const fileSignEl = questionEl.querySelector('.sd-file__sign');
        const aEl = fileSignEl.firstElementChild;
        if (aEl) {
          const suffix = aEl.href.split('.').pop();
          if (['png', 'jpg', 'jpeg', 'webp'].includes(suffix) && !fileSignEl.innerHTML.includes('src')) {
            fileSignEl.innerHTML = `
              ${fileSignEl.innerHTML}
              <img src="${aEl.href}?${new Date().getTime()}"
              crossorigin="anonymous" style="position: absolute;left: 0; top: 0; right: 0; bottom: 0; width: 100%; height: 100%;" />
            `;
          }
        }
      }
    });
    // 在每一次上传文件前的处理
    survey.onUploadFiles.add((survey, options) => {
      options.files.forEach((file) => {
        requestUploadFile(file).then((url) => {
          options.callback(
            'success',
            options.files.map((file) => ({
              file,
              content: url,
            })),
          );
        });
      });
    });
    // 在每一次错误提示之前的处理
    survey.onErrorCustomText.add((survey, options) => {
      const tipCn = {
        'Response required.': '此选项必填。',
        'The file size should not exceed 100 KB.': '文件大小不得超过100KB。',
        'The file size should not exceed 10.00 MB.': '文件大小不得超过10MB。',
      };
      if (tipCn[options.text]) options.text = tipCn[options.text];
    });
    // 在每一次问题隐藏状态更改时的处理
    survey.onVisibleChanged.add((sender, { name, visible, question }) => {
      this.$emit('visibleChanged', name, visible);
      // 当前不为初次渲染时触发的函数且修改了当页是否隐藏问题
      if (this.getPageNo() > -1 && this.getPageNo() === question.page.num - 1) {
        const pageInfoEl = document.querySelector('.page-question-count');
        if (!pageInfoEl) return;
        let count = 0;
        question.page.elements?.forEach((element) => {
          if (element.isVisible && !element.isPanel) count += 1;
          element.elements?.forEach((panel_element) => {
            if (panel_element.isVisible) count += 1;
          });
        });
        pageInfoEl.innerHTML = `共计${count}个问题`;
      }
    });
    // 每一次答案更改时的操作
    survey.onValueChanged.add(this.onValueChanged);
    // 在每一次当前页面更改时的操作
    survey.onCurrentPageChanged.add(this.onCurrentPageChanged);

    return {
      QUESTIONNAIRE_STATUS,
      survey,
      isShowLoading: false,
      loadingText: '下载中...',
    };
  },
  methods: {
    // 渲染风险信息函数
    renderRiskInfo(questionName, questionId) {
      const isOpenContent = this.questionnaireStatus === QUESTIONNAIRE_STATUS.PREVIEW;
      const riskData = this.riskObject[questionName];
      const riskEl = document.querySelector(`.sv-riskBox__${questionId}`);
      // 无风险数据或者数据等级为无风险不渲染
      if (!riskData || riskData.level === RISK_STATUS.NO || riskData.level === RISK_STATUS.TO_BE_CONFIRMED) {
        riskEl.innerHTML = '';
        return;
      }
      riskEl.innerHTML = `
      <div style="display: flex; justify-content: space-between; align-items: center;margin-top: 20px;">
        <p class="results-title">评审结果：</p>
        <div class="risk-box">
          <div class="risk-box__item red">发现风险</div><div class="risk-box__item">未发现风险</div>
        </div>
      </div>
      <div class="card t-card t-card--bordered t-card--shadow-hover" style="margin-top: 10px">
        <div class="t-card__header t-card__title--bordered" style="width: 100%">
          <b>风险描述：
            <span class="risk-desc text-content">
            ${riskData.description ?? '暂无描述'}
            </span>
          </b>
        </div>
        <div class="t-card__header t-card__title--bordered" style="width: 100%">
          <b>风险等级：
            <span class="grade-content" style="background-color:
            ${riskOptions[riskData.level ?? RISK_STATUS.NO].backgroundColor}">
            ${riskOptions[riskData.level ?? RISK_STATUS.NO].label}
            </span>
          </b>
        </div>
        <div class="t-card__header t-card__title--bordered risk-label" style="width: 100%">
          <b>风险标签：</b>
        </div>
        <!--法律依据-->
        <div class="t-card__header t-card__title--bordered" style="width: 100%">
          <div class="t-card__header-wrapper"><b>法律依据：</b></div>
          <div class="t-card__actions open-or-off open-or-off-law"
          ${isOpenContent ? 'style="display:none"' : 'style="transform: rotate(0deg)"'}
          ><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="t-fake-arrow t-collapse-panel__icon--default"><path d="M3.75 5.7998L7.99274 10.0425L12.2361 5.79921" stroke="black" stroke-opacity="0.9" stroke-width="1.3"></path></svg></div>
        </div>
        <div class="t-card__body basis-of-law" ${isOpenContent ? '' : 'style="display: none"'}>
          <div class="text-content">
            ${riskData.law ?? '暂无法律依据'}
          </div>
        </div>
        <!--标准依据-->
        <div class="t-card__header t-card__title--bordered" style="width: 100%">
          <div class="t-card__header-wrapper"><b>标准依据：</b></div>
          <div class="t-card__actions open-or-off open-or-off-standard"
          ${isOpenContent ? 'style="display:none"' : 'style="transform: rotate(0deg)"'}
          ><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="t-fake-arrow t-collapse-panel__icon--default"><path d="M3.75 5.7998L7.99274 10.0425L12.2361 5.79921" stroke="black" stroke-opacity="0.9" stroke-width="1.3"></path></svg></div>
        </div>
        <div class="t-card__body basis-of-standard" ${isOpenContent ? '' : 'style="display: none"'}>
          <div class="text-content">
            ${riskData.standard ?? '暂无标准依据'}
          </div>
        </div>
        <!--合规案例参考-->
        <div class="t-card__header t-card__title--bordered" style="width: 100%">
          <div class="t-card__header-wrapper"><b>合规案例参考</b></div>
          <div class="t-card__actions open-or-off open-or-off-case"
          ${isOpenContent ? 'style="display:none"' : 'style="transform: rotate(0deg)"'}
          ><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" class="t-fake-arrow t-collapse-panel__icon--default"><path d="M3.75 5.7998L7.99274 10.0425L12.2361 5.79921" stroke="black" stroke-opacity="0.9" stroke-width="1.3"></path></svg></div>
        </div>
        <div class="t-card__body basis-of-case" ${isOpenContent ? '' : 'style="display: none"'}>
          <div class="text-content">
            <p class="margin-b-20">${riskData.compliance ?? '暂无案例参考'}</p>
          </div>
        </div>
      </div>
      `;
      // 添加风险标签
      const riskLabelHeader = riskEl.querySelector('.t-card__header.risk-label');
      const labelArr = riskData.label ? JSON.parse(riskData.label) : [];
      const typeArr = riskData.type ? JSON.parse(riskData.type) : [];
      typeArr.forEach((label) => {
        const tagEl = document.createElement('span');
        tagEl.className = 'risk-desc content-red tag';
        tagEl.innerHTML = `
            <svg data-v-712d455c="" fill="none" viewBox="0 0 16 16" width="1em" height="1em" class="t-icon t-icon-discount icon" style="margin-right: 3px">
              <path fill="currentColor" d="M7.84 5.01A2 2 0 115 7.84 2 2 0 017.84 5zm-.7.7a1 1 0 10-1.42 1.42 1 1 0 001.41-1.41z" fill-opacity="0.9"></path>
              <path fill="currentColor" d="M2 7.95V2h5.95a1 1 0 01.7.3l6.14 6.13a1 1 0 010 1.41L9.84 14.8a1 1 0 01-1.41 0L2.29 8.66A1 1 0 012 7.95zM7.95 3l6.13 6.13-4.95 4.95L3 7.95V3h4.95z" fill-opacity="0.9" fill-rule="evenodd" clip-rule="evenodd"></path>
            </svg>
            <b>${label}</b>
            `;
        riskLabelHeader.appendChild(tagEl);
      });
      labelArr.forEach((label) => {
        const tagEl = document.createElement('span');
        tagEl.className = 'risk-desc content-yellow tag';
        tagEl.innerHTML = `
            <svg data-v-712d455c="" fill="none" viewBox="0 0 16 16" width="1em" height="1em" class="t-icon t-icon-discount icon" style="margin-right: 3px">
              <path fill="currentColor" d="M7.84 5.01A2 2 0 115 7.84 2 2 0 017.84 5zm-.7.7a1 1 0 10-1.42 1.42 1 1 0 001.41-1.41z" fill-opacity="0.9"></path>
              <path fill="currentColor" d="M2 7.95V2h5.95a1 1 0 01.7.3l6.14 6.13a1 1 0 010 1.41L9.84 14.8a1 1 0 01-1.41 0L2.29 8.66A1 1 0 012 7.95zM7.95 3l6.13 6.13-4.95 4.95L3 7.95V3h4.95z" fill-opacity="0.9" fill-rule="evenodd" clip-rule="evenodd"></path>
            </svg>
            <b>${label}</b>
            `;
        riskLabelHeader.appendChild(tagEl);
      });
      // 添加文件下载
      const caseBasisHeader = riskEl.querySelector('.t-card__body.basis-of-case');
      const fileArr = riskData.file ? riskData.file.split(',') : [];
      fileArr.forEach((path) => {
        if (!path) return;
        const name = path.split('/').pop();
        const aEl = document.createElement('a');
        aEl.className = 'file-content';
        aEl.href = FILE_URL_PREFIX + path;
        aEl.innerHTML = `
            <svg width="1em" height="1em" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M11 11.5H5V12.5H11V11.5Z" fill="currentColor" fill-opacity="0.9"></path>
              <path d="M2.5 1.92191C2.5 1.33727 3.02005 1 3.49534 1L8.7929 1.00007C9.05812 1.00007 9.31246 1.10543 9.5 1.29296L13.2071 5.00007C13.3946 5.18761 13.5 5.44196 13.5 5.70718V14.0782C13.5 14.6628 12.9799 15.0001 12.5047 15.0001L3.49534 15C3.02005 15 2.5 14.6627 2.5 14.0781V1.92191ZM3.5 2V14L12.5 14.0001V6.01283H8.50005V2.00007L3.5 2ZM9.50005 5.01283H11.8056L9.50005 2.70722V5.01283Z" fill="currentColor" fill-opacity="0.9"></path>
            </svg>
            <span class="file-name">${name}</span>
            `;
        caseBasisHeader.appendChild(aEl);
      });
      // 法律依据添加点击事件展开
      const openOrOffLaw = riskEl.querySelector('.open-or-off-law');
      openOrOffLaw.onclick = () => {
        const desc = riskEl.querySelector('.basis-of-law');
        if (desc.style.display !== 'none') {
          desc.style = 'display: none;';
          openOrOffLaw.style = 'transform: rotate(0deg)';
        } else {
          desc.style = 'display: block;';
          openOrOffLaw.style = 'transform: rotate(90deg)';
        }
      };
      // 标准依据添加点击事件展开
      const openOrOffStandard = riskEl.querySelector('.open-or-off-standard');
      openOrOffStandard.onclick = () => {
        const standard = riskEl.querySelector('.basis-of-standard');
        if (standard.style.display !== 'none') {
          standard.style = 'display: none;';
          openOrOffStandard.style = 'transform: rotate(0deg)';
        } else {
          standard.style = 'display: block;';
          openOrOffStandard.style = 'transform: rotate(90deg)';
        }
      };
      // 合规案例参考添加点击事件展开
      const openOrOffCase = riskEl.querySelector('.open-or-off-case');
      openOrOffCase.onclick = () => {
        const basisCase = riskEl.querySelector('.basis-of-case');
        if (basisCase.style.display !== 'none') {
          basisCase.style = 'display: none;';
          openOrOffCase.style = 'transform: rotate(0deg)';
        } else {
          basisCase.style = 'display: block;';
          openOrOffCase.style = 'transform: rotate(90deg)';
        }
      };
      //  else {
      //   riskBox.innerHTML = `
      //   <div style="display: flex; justify-content: space-between; align-items: center;">
      //     <p class="results-title">评审结果：</p>
      //     <div>
      //       <button class="risk-btn risk-btn-1">发现风险</button><button class="risk-btn risk-btn-2 is-active">未发现风险</button>
      //     </div>
      //   </div>
      //   `;
      //   questionEl.appendChild(riskBox);
      // }
      // <p class="font-bold margin-b-20">《个人信息保护法》第二十一条</p>
      // <p class="margin-b-20">个人信息处理者委托处理个人信息的，应当与受托人约定委托处理的目的、期限、处理方式、个人信息的种类、保护措施以及双方的权利和义务等，并<b style="color: #e34d59">对受托人的个人信息处理活动进行监督。</b></p>
      // <p class="margin-b-20">受托人应当按照约定处理个人信息，不得超出约定的处理目的、处理方式等处理个人信息;委托合同不生效、无效、被撤销或者终止的，受托人应当将个人信息返还个人信息处理者或者予以删除，不得保留。</p>
      // <p>未经个人信息处理者同意，受托人不得转委托他人处理个人信息。</p>
      // <p class="font-bold margin-b-20">GB/T 35273一2020《信息安全技术 个人信息安全规范》</p>
      // <p class="margin-b-20">9.1 委托处理</p>
      // <p class="margin-b-20" style="color: #e34d59"><b>d) 个人信息控制者应对受委托者进行监督，方式包括但不限于：</b></p>
      // <p class="margin-b-20" style="color: #e34d59"><b>1) 通过合同等方式规定受委托者的责任和义务;</b></p>
      // <p style="color: #e34d59"><b>2) 对受委托者进行审计。</b></p>
    },
    // PDF下载的操作
    async beforeDownload({ html2pdf, options, pdfContent }) {
      this.isShowLoading = true;
      // 为所有a标签在生成Pdf之后生成超链接
      options.enableLinks = true;
      // pdf换页规则
      options.pagebreak = {
        // avoid-all 不拆分任何元素
        mode: 'avoid-all',
      };

      const worker = html2pdf();
      const sdPageEl = pdfContent.querySelector('.sd-page');
      const questionEls = [...sdPageEl.children];
      for (let i = 0; i < questionEls.length; i += 10) {
        this.loadingText = `下载中...（${((i / questionEls.length) * 100).toFixed(0)}%）`;
        sdPageEl.innerHTML = '';
        sdPageEl.append(...questionEls.slice(i, i + 10));
        // eslint-disable-next-line no-await-in-loop
        await worker
          .set(options)
          .from(pdfContent)
          .toContainer()
          .toCanvas()
          .toPdf()
          .get('pdf')
          .then((pdf) => {
            pdf.canvas.getContext('2d', {
              willReadFrequently: true,
            });
            if (i + 10 < questionEls.length) pdf.addPage();
          });
      }

      worker.save();
      sdPageEl.innerHTML = '';
      sdPageEl.append(...questionEls);
      this.isShowLoading = false;
      this.$bus.$emit('downloadingReport');
    },
    // survey初始化
    init(surveyJson, needJumpPage) {
      if (!surveyJson) return;
      // 重新初始化后需要跳转回之前页面的处理
      if (needJumpPage) {
        const no = this.getPageNo() ?? 0;
        this.changeSurveyJson(surveyJson);
        this.changePageNoForcing(no);
        return;
      }
      this.changeSurveyJson(surveyJson);
    },
    // 答案更改的操作
    onValueChanged(sender) {
      this.$emit('input', sender.data);
    },
    // 当前页面更改时的操作
    onCurrentPageChanged() {
      this.$emit('currentPageChanged', this.survey.currentPageNo);
    },
    // 更改答案数据
    changeAnswerData(obj) {
      this.survey.data = obj;
    },
    // 更改问题json
    changeSurveyJson(json) {
      this.survey.fromJSON(json);
    },
    // 更改当前页面（需数据验证）
    changePageNo(no) {
      if (this.survey.currentPageNo === no) return;
      if (this.survey.hasPageErrors()) {
        this.$message.error('请完善本页问题后跳转其他页');
        return;
      }
      this.survey.currentPageNo = no;
    },
    // 更改当前页面
    changePageNoForcing(no) {
      this.survey.currentPageNo = no;
    },
    // 设置答案值
    setValue(name, value) {
      this.survey.setValue(name, value);
    },
    // 设置选择其他时的答案值
    setComment(name, value) {
      this.survey.setComment(name, value);
    },
    // 用name获取问题详细信息
    getQuestionByName(name) {
      return this.survey.getQuestionByName(name);
    },
    // 获取当前页数
    getPageNo() {
      return this.survey.currentPageNo;
    },
  },
};
</script>

<style lang="less" scoped>
.survey-content {
  height: calc(100vh - 265px);
  overflow-y: auto;
}
.survey {
  --primary: #0151d5;
  --primary-light: #ecf2fe;
  background-color: white;
  &.preview {
    --foreground-disabled: #333;
    /deep/ .sd-item--checked .sd-item__decorator {
      background: var(--primary, #19b394);
    }
    /deep/ .sd-boolean--disabled .sd-boolean__thumb,
    .sd-boolean--disabled .sd-boolean__label {
      color: var(--primary, rgba(22, 22, 22, 0.25));
    }
    /deep/ .sd-file__choose-btn {
      display: none;
    }
    /deep/ .sd-file--single-image .sd-file__sign a {
      color: #333;
    }
    /deep/ .sd-page__title .sv-vue-title-additional-div {
      text-align: center;
    }
    // /deep/ .sd-radio--checked.sd-radio--disabled .sd-radio__decorator:after {
    //   background-color: var(--primary);
    // }
  }
  /deep/ .sd-question--disabled .sd-table__cell {
    opacity: 1;
  }
  /deep/ .sd-page__row {
    border: 1px solid #f3f3f3;
  }
  /deep/ .sd-page__title {
    font-size: 20px;
    padding: 10px;
    border-bottom: 1px solid #e7e7e7;
  }
  /deep/ .sd-description {
    display: none;
  }
  /deep/ .sd-navigation__complete-btn {
    display: none;
  }
  /deep/ .button-box__content {
    position: relative;
    display: flex;
    align-items: center;
    .button-box__item {
      width: 14px;
      height: 14px;
    }
    .assigned-name {
      z-index: 9;
      position: absolute;
      top: 20px;
      left: 100%;
      transform: translate(-58%, 0) scale(0.8);
      width: max-content;
      padding: 3px 10px;
      font-size: 14px;
      font-weight: 400;
      color: #2c2c2c;
      background: #f3f3f3;
      border-radius: 5px;
      box-shadow: 0px 1px 2px 1px rgba(51, 51, 51, 0.1);
    }
    .text {
      font-size: 12px;
      color: #266fe8;
      position: relative;
      top: 1px;
    }
  }
  /deep/ .sv-vue-title-additional-div {
    flex: 1;
    .sv-tip-content {
      display: inline-block;
      position: relative;
      &:hover {
        .t-popup {
          display: inline;
        }
      }
      .sv-tip-img {
        width: 14px;
        height: 14px;
        cursor: pointer;
        position: relative;
        top: 1.3px;
      }
      .t-popup {
        display: none;
        position: absolute;
        width: 191px;
        top: -4px;
        left: 16px;
        .t-popup__content {
          color: #666;
          font-size: 12px;
          line-height: 15px;
        }
      }
    }
  }
  /deep/ .sv-riskBox {
    .results-title {
      font-size: 15px;
      font-weight: 600;
      color: #333;
    }
    .risk-box {
      display: flex;
      padding: 2px;
      background: #f3f3f3;
      border-radius: 3px;
      // align-items: center;
      .risk-box__item {
        width: 86px;
        height: 28px;
        border-radius: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: rgba(0, 0, 0, 0.6);
        &.red {
          background: #f36d78;
          color: rgba(255, 255, 255, 0.9);
        }
      }
    }
    .risk-desc {
      font-weight: normal;
      word-wrap: break-word;
    }
    .open-or-off {
      transform: rotate(90deg);
      cursor: pointer;
    }
    .grade-content {
      color: white;
      font-weight: 400;
      font-size: 12px;
      padding: 5px 8px;
      border-radius: 3px;
    }
    .tag {
      font-size: 12px;
      padding: 4px 8px 4px 4px;
      border-radius: 3px;
    }
    .file-content {
      display: flex;
      align-items: center;
      margin-bottom: 5px;
      .file-name {
        font-size: 12px;
        text-decoration: underline;
        margin-left: 5px;
      }
    }
    .content-red {
      border: 1px solid #e34d59;
      color: #e34d59;
      background: #fdecee;
    }
    .content-yellow {
      border: 1px solid #ed7b2f;
      color: #ed7b2f;
      background: #fef3e6;
    }
    .t-card__body {
      background-color: #f3f3f3;
    }
    .t-card__header {
      justify-content: flex-start;
      flex-wrap: wrap;
      .tag {
        margin: 2px;
      }
    }
    .text-content {
      /*文字换行  汉字和英文数字字符也适配*/
      width: inherit;
      white-space: normal;
      word-break: break-all;
      word-wrap: break-word;
    }
    .margin-b-20 {
      margin-bottom: 20px;
    }
    .font-bold {
      font-weight: bold;
    }
  }
}
</style>
